package com.xsd.awen.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 *  aes
 * @author Administrator
 *
 */
public class Cipher {
    static Logger logger = LoggerFactory.getLogger(Cipher.class);

    // 16
    private static byte[] KEY;

    private static String CHAR_SET = "utf-8";

    static {
        try {
            KEY = "7y12#$%6tf8uijY7".getBytes(CHAR_SET);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    // 加密
    public static String encrypt(String value) {
        SecretKeySpec skeySpec = new SecretKeySpec(KEY, "AES");
        try {
            javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
            cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(value.getBytes(CHAR_SET));
            return Base64.getEncoder().encodeToString(encrypted);
        }catch (Exception e){
            logger.error("aes error",e);
        }
        return null;
    }

    // 解密
    public static String decrypt(String value){
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(KEY, "AES");
            javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(javax.crypto.Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 =  Base64.getDecoder().decode(value);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,CHAR_SET);
                return originalString;
            } catch (Exception e) {
                logger.error("aes error",e);
                return null;
            }
        } catch (Exception ex) {
            logger.error("aes error",ex);
            return null;
        }
    }


}